const Review = require("../models/review");
const redisClient = require('../config/redis');

// 搜索和分页获取评论
exports.searchReviews = async (req, res) => {
  try {
    const { content, begin, end, page = 1, limit = 15 } = req.body;
    const cacheKey = `searchReviews:${content}:${begin}:${end}:${page}:${limit}`;

    // 尝试从 Redis 获取缓存
    const cachedData = await redisClient.get(cacheKey);
    if (cachedData) {
      console.log('从缓存中获取数据');
      return res.json(JSON.parse(cachedData));
    }

    const reviews = await Review.searchReviews(content, begin, end, page, limit);

    // 将结果存入 Redis 缓存
    await redisClient.setEx(cacheKey, 60, JSON.stringify(reviews));
    res.json(reviews);
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

// 获取单个评论
exports.getReviewsById = async (req, res) => {
  try {
    const { id } = req.params;
    const cacheKey = `review:${id}`;

    const cachedData = await redisClient.get(cacheKey);
    if (cachedData) {
      console.log('从缓存中获取数据');
      return res.json(JSON.parse(cachedData));
    }

    const review = await Review.findById(id);
    if (!review) {
      return res.status(404).json({ error: "评论不存在" });
    }

    await redisClient.setEx(cacheKey, 60, JSON.stringify(review));
    res.json(review);
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

// 根据电影 ID 获取评论
exports.getReviewsByMovieId = async (req, res) => {
  try {
    const { movieId } = req.params;
    const { sort = "created_at", page = 1, limit = 10 } = req.query;
    const validSortTypes = ["created_at", "hot"];
    
    if (!validSortTypes.includes(sort)) {
      return res.status(400).json({ error: "无效的排序类型" });
    }

    const cacheKey = `reviewsByMovieId:${movieId}:${sort}:${page}:${limit}`;
    const cachedData = await redisClient.get(cacheKey);
    
    if (cachedData) {
      console.log('从缓存中获取数据');
      return res.json(JSON.parse(cachedData));
    }

    const reviews = await Review.findAllByMovieId(movieId, sort, page, limit);
    await redisClient.setEx(cacheKey, 60, JSON.stringify(reviews));
    res.json(reviews);
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

// 获取评论（带分页和排序）
exports.getReviewsWithPost = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, sort = "likes", order = "DESC" } = req.body;
    const cacheKey = `reviewsWithPost:${page}:${pageSize}:${sort}:${order}`;

    const cachedData = await redisClient.get(cacheKey);
    if (cachedData) {
      console.log('从缓存中获取数据');
      return res.json(JSON.parse(cachedData));
    }

    const reviews = await Review.findWithPaginationAndSort(
      parseInt(page),
      parseInt(pageSize),
      sort,
      order
    );

    await redisClient.setEx(cacheKey, 60, JSON.stringify(reviews));
    res.json(reviews);
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

// 添加评论
exports.addReview = async (req, res) => {
  try {
    const { movie_id, user_rating, content } = req.body;
    const user_id = req.user.id;
    
    const reviewId = await Review.create({
      movie_id,
      user_id,
      user_rating,
      content,
    });

    // 清除相关缓存
    await redisClient.deletePattern(`reviewsByMovieId:${movie_id}:*`); // 使用通配符删除
    await redisClient.deletePattern('searchReviews:*'); // 清除所有搜索缓存
    await redisClient.del('allReviews');

    res.status(201).json({
      status: 201,
      data: { reviewId },
    });
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

// 删除评论
exports.deleteReview = async (req, res) => {
  try {
    const { id } = req.params;
    const review = await Review.findById(id);
    
    if (!review) {
      return res.status(404).json({ error: "评论不存在" });
    }
    if (review.user_id !== req.user.id && !req.user.isAdmin) {
      return res.status(403).json({ error: "您没有权限删除此评论" });
    }

    await Review.delete(id);

    // 清除相关缓存
    await redisClient.del(`review:${id}`);
    await redisClient.deletePattern(`reviewsByMovieId:${review.movie_id}:*`);
    await redisClient.deletePattern('searchReviews:*');
    await redisClient.del('allReviews');

    res.json({ message: "评论删除成功" });
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

// 更新评论
exports.updateReview = async (req, res) => {
  try {
    const { id } = req.params;
    const { user_rating, content } = req.body;
    const user_id = req.user.id;
    
    const review = await Review.findById(id);
    if (!review) {
      return res.status(404).json({ error: "评论不存在" });
    }
    if (review.user_id !== req.user.id && !req.user.isAdmin) {
      return res.status(403).json({ error: "您没有权限修改此评论" });
    }

    await Review.update(id, { user_id, user_rating, content });

    // 清除相关缓存
    await redisClient.del(`review:${id}`);
    await redisClient.deletePattern(`reviewsByMovieId:${review.movie_id}:*`);
    await redisClient.deletePattern('searchReviews:*');
    await redisClient.del('allReviews');

    res.json({ message: "评论更新成功" });
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

// 点赞评论
exports.likeReview = async (req, res) => {
  try {
    const { id } = req.params;
    const updatedReview = await Review.incrementLikes(id);

    // 清除相关缓存
    await redisClient.del(`review:${id}`);
    await redisClient.deletePattern(`reviewsByMovieId:${updatedReview.movie_id}:*`);
    await redisClient.deletePattern('searchReviews:*');
    await redisClient.del('allReviews');

    res.json({
      message: "点赞成功",
      likes: updatedReview.likes,
    });
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};